<template>
  <ContentWrap>
    <div class="btnWrap routeHeader">
    <div>
      <el-button @click="saveData" type="primary" v-hasPermi="['order:technolReviewTask:save']">保存</el-button>
      <el-button @click="submitData" type="primary" v-hasPermi="['order:technolReviewTask:submit']">提交</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </div>
  <div class="btnWrap">
    <el-button @click="addRow" type="primary" v-if="route.query.type === 'create'"
      >新增行</el-button
    >
  </div>
  </ContentWrap>
  
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :height="tableHeight" border>
    <el-table-column type="index" width="55" label="序号" align="left" fixed="left"/>
    <!-- 列定义 -->
    <el-table-column label="任务单号" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.taskNumber }}
      </template>
    </el-table-column>
    <el-table-column label="订单号" align="left" width="180">
      <template #default="scope">
        <el-select
          v-model="scope.row.orderNumber"
          placeholder="请选择订单号"
          filterable
          remote
          :remote-method="filterOptions"
          @change="handleChange(scope.$index, scope.row.orderNumber)"
          class="!w-140px"
        >
          <el-option
            v-for="(dict, index) in filteredOptions"
            :key="index"
            :label="dict.orderNumber"
            :value="dict.orderNumber"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="客户名称" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.customerName }}
      </template>
    </el-table-column>
    <el-table-column label="订单类型" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.MARKET_ORDER_TYPE" :value="scope.row.dictOrderType" />
      </template>
    </el-table-column>
    <el-table-column label="产品编号" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <el-select
          v-model="scope.row.productNumber"
          placeholder="请选择产品编号"
          filterable
          remote
          :remote-method="filterCpOptions"
          @change="handleChangeCp(scope.$index, scope.row.productNumber)"
          class="!w-140px"
        >
          <el-option
            v-for="(dict, index) in cpFilteredOptions"
            :key="index"
            :label="dict.productNumber"
            :value="dict.productNumber"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="产品名称" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.productName }}
      </template>
    </el-table-column>
    <el-table-column label="产品规格" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.productStandard }}
      </template>
    </el-table-column>
    <el-table-column label="单位" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{scope.row.partUnit}}
      </template>
    </el-table-column>
    <el-table-column label="订单数量" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.orderQuantity }}
      </template>
    </el-table-column>
    <el-table-column label="订单日期" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.orderDate }}
      </template>
    </el-table-column>
    <el-table-column label="发货日期" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.deliveryDate }}
      </template>
    </el-table-column>
    <el-table-column label="任务类型" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.ORDER_TECHNOL_TASK_TYPE" :value="scope.row.dictTaskType" />
      </template>
    </el-table-column>
    <el-table-column label="变更类型" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.CHANGE_TYPE" :value="scope.row.dictChangeType" />
      </template>
    </el-table-column>
    <el-table-column label="版本号" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        {{ scope.row.version }}
      </template>
    </el-table-column>
    <el-table-column label="项目合同" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <span style="cursor: pointer" @click="previewFile(scope.$index)">{{
          scope.row.fileName
        }}</span>
      </template>
    </el-table-column>
    <el-table-column label="状态" align="left" width="180" :class="'custom-header'">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.ORDER_TECHNOL_TASK_STATUS" :value="scope.row.dictTaskStatus" />
      </template>
    </el-table-column>
    <el-table-column label="备注" align="left" width="180" :class="'remark'">
      <template #default="scope">
        {{ scope.row.remark }}
      </template>
    </el-table-column>
    <el-table-column label="操作" align="left" min-width="110" fixed="right">
      <template #default="scope">
        <!-- 删除按钮 -->
        <el-button
          v-if="route.query.type === 'create'"
          link
          type="danger"
          @click="deleteRow(scope.$index)"
          >删除行</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  </ContentWrap>
  
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router'
  import { DICT_TYPE } from '@/utils/dict'
  import * as TechnolReviewTaskApi from '@/api/orderManagement/technolReviewTask'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  const { push } = useRouter()
  const loading = ref(true)
  let title = ref('')
  const list = ref<any>([])
  let listOption = ref<any>([])
  let filteredOptions = ref<any>([])
  let cpOptions = ref<any>([])
  let cpFilteredOptions = ref<any>([])
  //模糊查询
  const filterOptions = async (query) => {
    filteredOptions = await listOption.filter((option) => option.orderNumber.includes(query))
  }

  //获取订单号下拉选择器选中的值
  const handleChange = async (index, value) => {
    list.value[index].productNumber = ''
    list.value[index].productName = ''
    list.value[index].productStandard = ''
    list.value[index].dictUnit = ''
    list.value[index].orderQuantity = ''
    list.value[index].deliveryDate = ''
    list.value[index].dictChangeType = ''
    for (let i = 0; i < listOption.length; i++) {
      if (listOption[i].orderNumber == value) {
        list.value[index].customerName = listOption[i].customerName
        list.value[index].dictOrderType = listOption[i].dictOrderType
        list.value[index].orderDate = listOption[i].orderDate
        list.value[index].dictChangeType = listOption[i].dictChangeType
        list.value[index].dictTaskType = listOption[i].dictTaskType
        list.value[index].filePath = listOption[i].filePath
        list.value[index].fileName = listOption[i].fileName
        getProductRelationPage(listOption[i].orderNumber)
      }
    }
  }

  //产品编号模糊查粗寻
  const filterCpOptions = async (query) => {
    cpFilteredOptions = await cpOptions.filter((option) => option.productNumber.includes(query))
  }
  //获取产品编号下拉选择器选中的值
  const handleChangeCp = async (index, value) => {
    for (let i = 0; i < cpOptions.length; i++) {
      if (cpOptions[i].productNumber == value) {
        list.value[index].productName = cpOptions[i].productName
        list.value[index].productStandard = cpOptions[i].productStandard
        list.value[index].partUnit = cpOptions[i].partUnit
        list.value[index].dictTaskType = cpOptions[i].dictTaskType
        list.value[index].orderQuantity = cpOptions[i].orderQuantity
        list.value[index].deliveryDate = cpOptions[i].deliveryDate
        list.value[index].dictChangeType = cpOptions[i].dictChangeType
        list.value[index].remark = cpOptions[i].remark
        list.value[index].version = cpOptions[i].version
      }
    }
  }
  const getList = async () => {
    loading.value = true
    try {
      // 请求数据的逻辑
    } finally {
      loading.value = false
    }
  }
  const addRow = () => {
    const newRow = {
      taskNumber: undefined, //任务单号
      orderNumber: undefined, //订单编号
      customerName: undefined, //客户简称
      dictOrderType: undefined, //订单类型
      productNumber: undefined, //产品编号
      productName: undefined, //产品名称
      productStandard: undefined, //产品规格
      partUnit: undefined, //单位
      orderQuantity: undefined, //订单数量
      orderDate: undefined, //订单日期
      deliveryDate: undefined, //发货日期
      dictTaskType: undefined, //任务类型
      dictChangeType: undefined, //变更类型
      version: undefined, //版本号
      fileName: undefined, //项目合同
      filePath: undefined, //项目合同url
      dictTaskStatus: undefined, //任务状态
      remark: undefined
    }
    list.value.push(newRow)
  }

  const deleteRow = (index: number) => {
    list.value.splice(index, 1)
  }

  //附件预览
  const previewFile = (index) => {
    list.value[index]
    window.open(list.value[index].filePath)
  }

  //必填校验
  const check = async () => {
    let data = await list.value
    for (let i = 0; i < data.length; i++) {
      if (!data[i].orderNumber) {
        message.warning(t('订单号不能为空'))
        return false
      }

      if (!data[i].productNumber) {
        message.warning(t('产品编号不能为空'))
        return false
      }
    }
    return true
  }
  /**保存 */
  const saveData = async () => {
    const isFlag = await check()
    if (isFlag) {
      let type = route.query.type
      if (type === 'create') {
        let reqData = {
          submitFlag: 1,
          createList: list.value
        }
        await TechnolReviewTaskApi.createTechnolReviewTask(reqData)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/orderManagement/orderManagement/review/review')
      } else {
        let reqData = list.value
        reqData[0].submitFlag = 1
        message.success(t('common.updateSuccess'))
        await TechnolReviewTaskApi.updateTechnolReviewTask(reqData[0])
        tagsViewStore.delView(routes.currentRoute.value)
        push('/orderManagement/orderManagement/review/review')
      }
    }
  }
  /**提交 */
  const submitData = async () => {
    const isFlag = await check()
    if (isFlag) {
      let type = route.query.type
      if (type === 'create') {
        let reqData = {
          submitFlag: 2,
          createList: list.value
        }
        await TechnolReviewTaskApi.createTechnolReviewTask(reqData)
        message.success(t('common.createSuccess'))
        tagsViewStore.delView(routes.currentRoute.value)
        push('/orderManagement/orderManagement/review/review')
      } else {
        let reqData = list.value
        reqData[0].submitFlag = 2
        message.success(t('common.updateSuccess'))
        await TechnolReviewTaskApi.updateTechnolReviewTask(reqData[0])
        tagsViewStore.delView(routes.currentRoute.value)
        push('/orderManagement/orderManagement/review/review')
      }
    }
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/orderManagement/orderManagement/review/review')
  }
  //获取订单列表
  const getProductRelationPageAll = async () => {
    let params = {
      dictOrderStatus: '1',
      isQuote: '1',
      orderNumber: '',
      dictOrderType:10
    }
    const data = await TechnolReviewTaskApi.getProductRelationPageAll(params)
    listOption = data
    filteredOptions = data
  }
  //获取产品编号
  const getProductRelationPage = async (orderNumber) => {
    let params = {
      orderNumber: orderNumber
    }
    const data = await TechnolReviewTaskApi.getProductRelationPage(params)
    cpFilteredOptions = data
    cpOptions = data
  }
  //获取评审任务单详情
  const getDetail = async (id) => {
    const data = await TechnolReviewTaskApi.getTechnolReviewTask(id)
    if (data.orderNumber) {
      getProductRelationPage(data.orderNumber)
      list.value.push(data)
    }
  }
  // 初始化
  const tableHeight = ref(0)
  onMounted(async () => {
    tableHeight.value = document.body.clientHeight - 132  - 123
    let type = route.query.type
    if (type === 'create') {
      title.value = '新增评审任务单'
    } else {
      title.value = '编辑评审任务单'
    }
    if (route.query.id != 'undefined') {
      getDetail(route.query.id)
    }
    await getList()
    await getProductRelationPageAll()
  })
</script>
<style lang="scss" scoped>
  .contentView {
    padding: 10px;
    background: #fff;
  }
  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;
      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }
  .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .el-table .custom-header::before {
    content: '*';
    color: red;
    margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
  }
  :deep(.el-form .el-input, .el-form .el-input__wrapper, .el-form .el-textarea) {
    width: 100% !important;
  }
</style>
